﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace SampleWpf.Attributes
{
	public class EmailAttribute : ValidationAttribute
	{
		private string _defaultMessage = "the Email format is incorrect.";
		//邮箱的正则校验
		private readonly Regex _regex
		  = new(@"^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$");

		public EmailAttribute() : base()
		{
			base.ErrorMessage = _defaultMessage;
		}

		public EmailAttribute(string _regex) : base()
		{
			base.ErrorMessage = _defaultMessage;
			_regex = new(_regex);
		}

		public override bool IsValid(object? value)
		{
			if (value is null)
			{
				return false;
			}
			return _regex.IsMatch(value.ToString());
		}


	}
}
